<template>
	<view class="detail-page">
		<!-- 头部 -->
		<u-sticky offset-top="0" style="background: #fff; top: 0">
			<view class="page-title">
				<h3 class="title">{{ title }}</h3>
				<view v-if="dataSource.action">
					<u-button type="primary" text="下一阶段" size="mini" style="background: #5d7ca0; border-color: #5d7ca0" @click="handleNext"></u-button>
				</view>
				<view v-else class="ske">
					<u-skeleton rows="1" title loading titleHeight="40rpx"></u-skeleton>
				</view>
			</view>

			<view class="tabs">
				<u-tabs :list="dataSource.groupData" @click="click" :current="currentIndex" v-if="dataSource.groupData"></u-tabs>
				<view class="view-ske" v-else>
					<u-skeleton rows="1" title loading titleHeight="48rpx" titleWidth="100%"></u-skeleton>
				</view>
			</view>
		</u-sticky>

		<!-- 内容 -->
		<view v-for="(item, index) in currentItem" class="main" v-if="currentItem[0].data.length > 0">
			<u-transition :show="true" mode="fade-right">
				<view v-for="(subItem, subIndex) in item.data" class="main-group">
					<view class="group-title" v-if="subItem.groupTitle">
						<view class="group-text">{{ subItem.groupTitle }}</view>
					</view>
					<view v-if="subItem.type === 'form'">
						<u--form labelPosition="left" v-if="subItem.list.length > 0">
							<u-form-item :label="formItem.label" v-for="formItem in subItem.list">
								<u--input :value="formItem.value ? formItem.value : '-'" border="none" disabled></u--input>
							</u-form-item>
						</u--form>
						<Empty v-else />
					</view>
					<view v-if="subItem.type === 'list'" class="u-list-table">
						<u-list v-if="subItem.list.length > 0">
							<u-list-item v-for="(listItem, index) in subItem.list" :key="index" class="u-list-table-itam">
								<view class="list-table">
									<u-avatar :text="listItem.label.substring(0, 1)" fontSize="16" randomBgColor></u-avatar>

									<view class="list-content">
										<u--text :lines="3" :text="listItem.label" class="title"></u--text>
										<!-- <view class="title">{{ listItem.label }}</view> -->
										<view class="des">{{ listItem.des }}</view>
										<view class="des">{{ listItem.value }}</view>
									</view>
								</view>
							</u-list-item>
						</u-list>
						<Empty v-else />
					</view>
					<view v-if="subItem.type === 'file'">
						<u--form labelPosition="left" v-if="subItem.list.length > 0">
							<u-list>
								<u-list-item v-for="(listItem, index) in subItem.list" :key="index" class="u-file-list">
									<view style="display: flex" class="u-file-item" @click="handleView(listItem)">
										<u-icon name="file-text-fill"></u-icon>
										<text class="u-file-item-title">{{ listItem.label }}</text>
									</view>
								</u-list-item>
							</u-list>
						</u--form>
						<Empty v-else />
					</view>
					<view v-if="!subItem.type">
						<Empty />
					</view>
				</view>
			</u-transition>
		</view>
		<Empty v-else />

		<!-- 弹窗 -->
		<u-popup :show="show" @close="close" @open="open" mode="bottom" class="preview" safeAreaInsetBottom>
			<view class="view-content" @touchmove.stop>
				<view id="preview-doc" v-if="modalType === 'doc' || modalType === 'docx'"></view>

				<view id="preview-pdf" v-if="modalType === 'pdf' || modalType === 'pptx'"></view>

				<view class="preview-excel" v-if="modalType === 'xlsx' || modalType === 'xls'">
					<u-subsection :list="SheetNames" :current="current" @change="changeSub"></u-subsection>
					<view id="preview-excel"></view>
				</view>

				<view style="width: 100%; height: 100%" v-if="modalType === 'jpg' || modalType === 'jpeg' || modalType === 'png' || modalType === 'gif'">
					<img :src="imgUrl" alt="" style="width: 100%" />
				</view>
			</view>
			<view style="height: 20rpx; width: 100%"></view>
			<view class="close-btn">
				<u-button type="primary" text="关闭" @click="close" style="font-size: 28rpx !important; background-color: #5d7ca0; border-color: #5d7ca0"></u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
import { renderAsync } from 'docx-preview';

import Pdfh5 from 'pdfh5';
import 'pdfh5/css/pdfh5.css';

import * as xlsx from 'xlsx';
import canvasDatagrid from 'canvas-datagrid';

import request from '@/utils/request.js';
import { encrypt } from '@/utils/utils.js';
import globalConfig from '@/utils/globalConfig.js';
import Empty from '@/components/empty.vue';

export default {
	components: {
		Empty
	},
	data() {
		return {
			title: '',
			show: false,
			pdfh5: null,
			pdfUrl: '',
			excelUrl: '',
			SheetNames: [],
			current: 0,
			workbook: {},
			isShowDiv: true,
			currentIndex: 0,
			currentItem: [],
			dataSource: {},
			imgUrl: '',
			modalType: ''
		};
	},
	onPullDownRefresh() {
		this.hideToast();
		// 停止刷新
		let data = {
			...JSON.parse(localStorage.getItem('FIXED_PARAMS')),
			entityId: this.$route.query.id,
			logEntityName: this.$route.query.name
		};
		let params = encrypt(data);
		this.getList('enablePullDownRefresh', params);
	},
	onLoad() {
		console.log(this.$route.query);
		this.title = this.$route.query.title;

		let data = {
			...JSON.parse(localStorage.getItem('FIXED_PARAMS')),
			entityId: this.$route.query.id,
			logEntityName: this.$route.query.name
		};
		console.log(data);
		let params = encrypt(data);
		this.getList(null, params);
	},

	methods: {
		getList(isLoading, params) {
			if (!isLoading) {
				this.showToast();
			}

			request('/EnterpriseWeChatIMSSystemWorkbench/GetDetailPagesDataApi', 'POST', { ...params })
				.then((res) => {
					console.log('请求成功:', res);
					let data = JSON.parse(res.Data);
					console.log(data);
					if (data) {
						this.hideToast();
						this.dataSource = data;
						this.currentItem = [this.dataSource.groupData[this.currentIndex]];
					}
					if (isLoading) {
						uni.stopPullDownRefresh();
					}
				})
				.catch((err) => {
					console.error('请求失败:', err);
				});
		},

		changeSub(e) {
			this.isShowDiv = false;
			let that = this;
			this.current = e;
			let divs = document.getElementsByTagName('canvas-datagrid');
			divs[divs.length - 1].hidden = true;
			setTimeout(function () {
				let workbook = that.workbook;
				let n = that.SheetNames[that.current];
				const sheet = workbook.Sheets[`${n}`];
				const json = xlsx.utils.sheet_to_json(sheet);
				const grid = canvasDatagrid({
					parentNode: document.getElementById('preview-excel'),
					data: json, // json 是前面解析得到 sheet 对应的数据
					editable: false, // 表示不使用表格编辑
					autoResizeColumns: true // 列宽自适应
				});
				// grid.style.width = '100%';
				// grid.style.height = '100%';
				this.isShowDiv = true;
			}, 100);
		},

		click(e) {
			this.currentIndex = e.key;
			this.currentItem = [];
			setTimeout(() => {
				this.currentItem = [this.dataSource.groupData[this.currentIndex]];
			}, 10);
		},
		handleNext() {
			console.log('xiayi阶段');
			uni.showLoading({
				title: '正在推进',
				class: 'my-toast'
			});

			let that = this;
			let data = {
				...JSON.parse(localStorage.getItem('FIXED_PARAMS')),
				EntityId: this.$route.query.id,
				EntityName: this.$route.query.name
			};
			let params = encrypt(data);
			request('/EnterpriseWeChatIMSSystemWorkbench/NextStageModificationsApi', 'POST', { ...params })
				.then((res) => {
					console.log('请求成功:', res);
					if (res.Code === 0) {
						uni.hideLoading();
						console.log('code等于0');
						uni.showToast({
							title: res.Message,
							duration: 3000,
							icon: 'none'
						});

						setTimeout(() => {
							let data = {
								...JSON.parse(localStorage.getItem('FIXED_PARAMS')),
								entityId: that.$route.query.id,
								logEntityName: that.$route.query.name
							};
							let params = encrypt(data);
							that.getList(null, params);
						}, 3100);
					} else {
						uni.hideLoading();
						uni.showModal({
							title: '提示',
							content: res.Message,
							showCancel: false,
							success: function (res) {
								if (res.confirm) {
									console.log('用户点击确定');
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					}
				})
				.catch((err) => {
					console.error('请求失败:', err);
				});
		},
		clear() {
			this.title = '';
			this.show = false;
			this.pdfh5 = null;
			this.pdfUrl = '';
			this.excelUrl = '';
			this.SheetNames = [];
			this.current = 0;
			this.workbook = {};
			this.isShowDiv = true;
			this.currentIndex = 0;
			this.currentItem = [];
			this.dataSource = {};
		},
		handleView(item) {
			console.log(item);
			const type = item.des;
			this.modalType = type;
			let photoType = ['doc', 'docx', 'xls', 'xlsx', 'pdf', 'jpg', 'jpeg', 'png', 'gif', 'pptx'];
			if (photoType.includes(type)) {
				uni.showLoading({
					title: '正在加载文件',
					class: 'my-toast'
				});
				// 请求接口 获取base64

				let data = {
					...JSON.parse(localStorage.getItem('FIXED_PARAMS')),
					SharepointId: item.id
				};
				let params = encrypt(data);

				request('/EnterpriseWeChatIMSSystemWorkbench/PptxRichTextApi', 'POST', { ...params })
					.then((res) => {
						console.log('请求成功:', res);
						let data = JSON.parse(res.Data);
						console.log(data);
						if (data) {
							uni.hideLoading();
							this.show = true;
							let that = this;
							// 预览word
							if (type === 'doc' || type === 'docx') {
								console.log('是word');
								setTimeout(function () {
									let _blob = that.base64ToArrayBuffer(data);
									let preview = document.getElementById('preview-doc');
									//用docx-preview渲染
									renderAsync(_blob, preview).then((res) => {
										console.log('res---->', res);
									});
								}, 100);
							} else if (type === 'xls' || type === 'xlsx') {
								setTimeout(function () {
									let buffer = that.base64ToArrayBuffer(data);
									console.log(buffer, '二进制');
									const workbook = xlsx.read(buffer);
									console.log(workbook, 'workbook');
									that.workbook = workbook;
									that.SheetNames = workbook.SheetNames;
									const sheet = workbook.Sheets[that.SheetNames[that.current]]; // 这里取第 0 个 sheet

									console.log(sheet, 'sheet');
									const json = xlsx.utils.sheet_to_json(sheet);
									console.log(json, 'json');
									const grid = canvasDatagrid({
										parentNode: document.getElementById('preview-excel'),
										data: json, // json 是前面解析得到 sheet 对应的数据
										editable: false, // 表示不使用表格编辑
										autoResizeColumns: true // 列宽自适应
									});
									// grid.style.width = '100%';
									// grid.style.height = '100%';
									// grid.style.height = 'calc(100vh - 230px)';
								}, 100);
							} else if (type === 'pdf' || type === 'pptx') {
								setTimeout(function () {
									this.pdfh5 = new Pdfh5(document.getElementById('preview-pdf'), {
										pdfurl: 'data:application/pdf;base64,' + data
									});
								}, 100);
								// 'jpg', 'jpeg', 'png', 'gif'
							} else if (type === 'jpg' || type === 'jpeg') {
								this.imgUrl = 'data:image/jpeg;base64,' + data;
							} else if (type === 'png') {
								this.imgUrl = 'data:image/png;base64,' + data;
							} else if (type === 'gif') {
								this.imgUrl = 'data:image/gif;base64,' + data;
							}
						}
					})
					.catch((err) => {
						console.error('请求失败:', err);
					});

				// ======== end ========
			} else {
				uni.showToast({
					title: '该数据格式暂不支持预览',
					duration: 2000,
					icon: 'none',
					class: 'my-toast'
				});
			}
		},
		close() {
			this.show = false;
		},
		open() {
			// console.log('open');
		},
		// base转二进制
		base64ToArrayBuffer(base64) {
			let binaryString = window.atob(base64);
			let len = binaryString.length;
			let bytes = new Uint8Array(len);
			for (let i = 0; i < len; i++) {
				bytes[i] = binaryString.charCodeAt(i);
			}
			return bytes.buffer;
		},
		showToast() {
			uni.showLoading({
				title: '正在加载',
				class: 'my-toast'
			});
		},
		hideToast() {
			uni.hideLoading();
		}
	}
};
</script>

<style lang="scss">
.detail-page {
	.preview-excel {
		height: 100%;
		overflow: hidden;
	}
	.ske {
		width: 112rpx;
	}
	.view-ske {
		padding: 20rpx 24rpx 8rpx 24rpx;
	}
	background-color: rgba(234, 234, 234, 0.7);
	height: 100%;
	min-height: 100vh;
	.page-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		padding-bottom: 0;
	}
	.title {
		font-size: 32rpx;
		width: calc(100vw - 280rpx);
	}

	.tabs {
		padding: 0 6rpx;
		height: 88rpx;
	}
	.list-content {
		.title {
			font-size: 30rpx;
			color: #303133;
			align-items: center;
		}

		.des {
			margin-top: 10rpx;
			font-size: 24rpx;
			color: #909193;
			line-height: 36rpx;
		}
	}

	.preview {
	}

	.view-content {
		height: calc(100vh - 400rpx);
		overflow-y: auto;
		// padding-bottom: 20rpx;
	}
	.main {
		.main-group {
			margin-bottom: 30rpx;
			// background-color: #ccc;
			box-shadow: 0rpx 0rpx 200rpx #fff;
			// border:1px solid #fff;
			background: #fff;
			border-radius: 8rpx;
			margin: 30rpx;
			padding: 20rpx;
		}

		.group-title {
			display: flex;
			height: 52rpx;
			align-items: center;
			.group-text {
				font-size: 32rpx;
				color: #8f9ca2;
				margin-right: 20rpx;
			}
		}

		.list-table {
			display: flex;
			align-items: center;
			// margin-bottom: 15px;
			padding: 20rpx 0;
			.list-content {
				margin-left: 20rpx;
				font-size: 28rpx;
				view {
					margin-top: 10rpx;
				}
			}
		}
		.u-file-list {
			.u-file-item {
				padding: 14rpx 0;
				.u-file-item-title {
					margin-left: 20rpx;
					font-size: 28rpx;
				}
			}
		}
	}
	.u-list-table .u-list-table-itam + .u-list-table-itam {
		border-top: 2rpx solid rgb(214, 215, 217);
	}
	#preview-excel {
		width: 100%;
		height: calc(100% - 66rpx);
		overflow: auto;
	}
}

::v-deep {
	.u-popup__content {
		padding: 30rpx;
	}

	.u-list {
		height: auto !important;
	}

	.docx-wrapper {
		background-color: #fff;
		padding: 0;
	}
	.docx-wrapper > section.docx {
		width: 100% !important;
		padding: 0rem !important;
		min-height: auto !important;
		box-shadow: none;
		margin-bottom: 0;
	}
	.backTop,
	.pageNum,
	.loadingBar {
		display: none !important;
	}
	.pdfViewer {
		padding: 0 !important;
	}
	.u-form-item__body {
		padding: 10rpx 0 0 0;
	}
	.u-input {
		background: transparent !important;
	}
	.u-form-item__body__left__content__label,
	.uni-input-input {
		font-size: 28rpx;
	}
	.u-skeleton__wrapper__content__rows {
		display: none;
	}
	.u-skeleton {
		// width: 56px;
		width: 100%;
	}
	.u-skeleton__wrapper__content__title {
		width: 100% !important;
	}
	.u-skeleton__wrapper__content {
		width: 100%;
	}
	.u-empty {
		background: #fff;
		padding-bottom: 50rpx;
	}
	.u-form-item__body__left {
		width: auto !important;
	}
	.u-form-item__body__left {
		margin-right: 8rpx;
	}
	.u-icon__icon {
		// size="20"
		font-size: 44rpx !important;
		color: rgba(93, 124, 160, 0.5) !important;
	}
	.u-avatar {
		width: 80rpx !important;
		height: 80rpx !important;
	}
	// tabs
	.u-text .u-text__value {
		font-size: 28rpx !important;
	}
	.u-tabs__wrapper__nav__item__text {
		font-size: 30rpx;
	}
	.u-tabs__wrapper__nav {
		.u-tabs__wrapper__nav__item {
			height: 88rpx !important;
			line-height: 88rpx !important;
		}
	}
	.u-tabs__wrapper__nav__line {
		background-color: rgb(93, 124, 160) !important;
		width: 40rpx !important;
		height: 6rpx !important;
	}
	.u-button__text {
		font-size: 20rpx !important;
	}
	.u-button--mini {
		padding: 0 16rpx;
		height: 44rpx;
	}
	.close-btn {
		.u-button__text {
			font-size: 28rpx !important;
		}
	}
	.u-form-item__body {
		display: block;
		margin-bottom: 10rpx;
		.uni-input-input {
			color: rgba(0, 0, 0, 0.5);
		}
	}
}
</style>
